package com.lzq.chatroom_project.controller;

import com.lzq.chatroom_project.common.pojo.Result;
import com.lzq.chatroom_project.model.SensitiveWordTrie;
import com.lzq.chatroom_project.service.SensitiveWordService;
import com.lzq.chatroom_project.service.impl.SensitiveWordServiceImpl;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

@RestController
@RequestMapping("/sensitive_word")
public class SensitiveWordController {
    private static final Logger log = LoggerFactory.getLogger(SensitiveWordController.class);
    @Autowired
    private SensitiveWordService sensitiveWordService;
    @Autowired
    private SensitiveWordTrie sensitiveWordTrie;
    private Long lastBuiltTimeStamp = System.currentTimeMillis();

    @PostConstruct
    public void init() {
        // 加载敏感词库并初始化 Trie
        sensitiveWordService.loadSensitiveWords();
        sensitiveWordTrie.buildSensitiveTree(sensitiveWordService.getSensitiveWords());
    }

    @PostMapping("/add")
    public synchronized Result<String> addSensitiveWord(@RequestParam String word) {
        sensitiveWordService.addSensitiveWord(word);
        sensitiveWordTrie.addWord(word);
        return Result.success("敏感词已添加: " + word);
    }

    @PostMapping("/remove")
    public synchronized Result<String> removeSensitiveWord(@RequestParam String word) {
        sensitiveWordService.removeSensitiveWord(word);
        return Result.success("敏感词已删除: " + word);
    }

    @Scheduled(fixedRate = 5 * 60 * 1000) // 每隔300秒执行一次
    public void checkSensitiveWordTrie() {
        Set<String> sensitiveWordsRemoveBufferSet = sensitiveWordService.getsensitiveWordsRemoveBufferSet();
        log.info("开始检查sensitiveWordsRemoveBufferSet");
        if (sensitiveWordsRemoveBufferSet.size() > 10
                || (((System.currentTimeMillis() - lastBuiltTimeStamp) >= 60 * 60 * 1000)
                        && (!sensitiveWordsRemoveBufferSet.isEmpty()))) {
            for (String removedSensitiveWord : sensitiveWordsRemoveBufferSet) {
                sensitiveWordService.removeSensitiveWordFromList(removedSensitiveWord);
            }
            sensitiveWordTrie.buildSensitiveTree(sensitiveWordService.getSensitiveWords());
            lastBuiltTimeStamp = System.currentTimeMillis();
            log.info("sensitiveWordTrie已被重建");
        }
    }
}
